<template>
  <el-card style="height: 360px;border-radius:16px;">
    <div style="color: #000; font-weight: 700; font-size: 16px; margin-bottom: 10px;">学习总览</div>
    <div :id="id" :class="className" :style="{height:height,width:width}" />
  </el-card>
</template>

<script>
import echarts from 'echarts'
import resize from './mixins/resize'
import { dashLearnWeek } from '@/api/stat/stat'

export default {
  name: 'LineChartCourse',
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    id: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '200px'
    },
    height: {
      type: String,
      default: '200px'
    },
    title: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      chart: null
    }
  },
  mounted() {
    dashLearnWeek().then(res => {
      this.parseData(res.data)
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {

    // 处理数据
    parseData(data) {
      const dateList = []
      const learnUserList = []
      const finishUserList = []
      const avgTimeList = []

      for (let i = 0; i < data.length; i++) {
        const stat = data[i]
        dateList.push(stat.dateStr)
        learnUserList.push(stat.learnUser)
        finishUserList.push(stat.finishUser)
        avgTimeList.push(stat.avgTime)
      }

      const option = {
        title: {
          text: ''
        },
        tooltip: {
          trigger: 'axis',
          formatter: '{b} <br/>{a0} : {c0}<br/>{a1} : {c1}',
          axisPointer: { // 坐标轴指示器，坐标轴触发有效
            type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        legend: {
          data: ['学习人数', '学完人数']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        },
        xAxis: [
          {
            type: 'category',
            data: dateList
          }
        ],
        yAxis: [
          {
            type: 'value',
            minInterval: 1
          }
        ],
        series: [
          {
            name: '学习人数',
            type: 'bar',
            emphasis: {
              focus: 'series'
            },
            data: learnUserList
          },
          {
            name: '学完人数',
            type: 'bar',
            emphasis: {
              focus: 'series'
            },
            data: finishUserList
          }
        ]
      }

      this.initChart(option)
    },

    initChart(option) {
      this.chart = echarts.init(document.getElementById(this.id))
      this.chart.setOption(option)
    }
  }
}
</script>
